/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cw.view;

import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import org.cw.bean.Establishment;
import org.cw.bean.Reviews;
import org.cw.bo.EstablishmentBO;
import org.cw.bo.ReviewBO;

/**
 *
 * @author SVN - Team
 */
public class FromAddEditReview extends Form implements CommandListener, Runnable {

    public static final int ADD = 1;
    public static final int EDIT = 2;
    private ReviewBO reviewBO = ReviewBO.getInstance();
    private EstablishmentBO estBO = EstablishmentBO.getInstance();
    private static final String TITLE = "New Review";
    private MReviewer curDisplay;
    private FromListEstablishments frmListEst;
    private Command cmdAdd, cmdBack, cmdEdit, cmdOk, cmdCancel, cmdDone;
    private DateField dateOfReview;
    private ChoiceGroup cbbTypeOfMeal;
    private static final String typeOfMeal[] = {"dinner", "lunch", "breakfast"};
    private TextField txtCostOfMeal;
    private TextField txtComment;
    private RateItemComponent overallRate, rateOfServices, rateOfAtmosphere, rateOfFood;
    private Establishment est;
    private Alert msg;
    private FromViewEstablistment viewEst;
    private Image iconAdd;
    private StringItem titleAdd;
    private StringItem txtNote;
    private StringItem txtReviewOf;
    private int STAGE_FORM = 1;
    private Reviews obReviews;

    public FromAddEditReview(MReviewer curDisplay) {
        super(TITLE);
        this.curDisplay = curDisplay;
    }

    public void setEst(Establishment est, int STAGE_FORM) {
        this.est = est;
        this.STAGE_FORM = STAGE_FORM;
        init();
    }

    private void init() {
        if (STAGE_FORM == ADD) {
            try {
                iconAdd = Image.createImage("/addReview.png");
            } catch (Exception e) {
            }
            titleAdd = new StringItem("", "Add new a Review");
            cmdAdd = new Command("Add", Command.OK, 1);
            addCommand(cmdAdd);
        } else if (STAGE_FORM == EDIT) {
            this.setTitle("Information of Review");
            try {
                iconAdd = Image.createImage("/edit.png");
            } catch (Exception e) {
            }
            titleAdd = new StringItem("", "Edit a Review");
            cmdEdit = new Command("Save", Command.OK, 1);
            addCommand(cmdEdit);
        }
        titleAdd.setLayout(StringItem.LAYOUT_2);
        txtReviewOf = new StringItem("Establishment Name:", est.getName());
        append(iconAdd);
        append(titleAdd);
        append(txtReviewOf);
        dateOfReview = new DateField("Date Of Review (*)      ", DateField.DATE, null);
        dateOfReview.setDate(new Date());
        append(dateOfReview);
        cbbTypeOfMeal = new ChoiceGroup("Type Of Meal (*)             ", ChoiceGroup.POPUP, typeOfMeal, null);
        append(cbbTypeOfMeal);
        txtCostOfMeal = new TextField("Cost of the meal (*)", "", 15, TextField.NUMERIC);
        append(txtCostOfMeal);
        overallRate = new RateItemComponent("Overall rating", RateItemComponent.NO_EDIT_ABLE);
        append(overallRate);
        rateOfServices = new RateItemComponent("Rating for services", RateItemComponent.EDIT_ABLE);
        append(rateOfServices);
        rateOfAtmosphere = new RateItemComponent("Rating for atmosphere", RateItemComponent.EDIT_ABLE);
        append(rateOfAtmosphere);
        rateOfFood = new RateItemComponent("Rating for food itself", RateItemComponent.EDIT_ABLE);
        append(rateOfFood);
        txtComment = new TextField("Comments", "", 100, TextField.ANY);
        append(txtComment);
        txtNote = new StringItem("", "Note: The fields with (*) are required to complete the information.");
        append(txtNote);
        rateOfAtmosphere.setRateOverall(overallRate);
        rateOfAtmosphere.setRatingOfAtmosphere(rateOfAtmosphere);
        rateOfAtmosphere.setRatingOfFood(rateOfFood);
        rateOfAtmosphere.setRatingOfServices(rateOfServices);

        rateOfFood.setRateOverall(overallRate);
        rateOfFood.setRatingOfAtmosphere(rateOfAtmosphere);
        rateOfFood.setRatingOfFood(rateOfFood);
        rateOfFood.setRatingOfServices(rateOfServices);

        rateOfServices.setRateOverall(overallRate);
        rateOfServices.setRatingOfAtmosphere(rateOfAtmosphere);
        rateOfServices.setRatingOfFood(rateOfFood);
        rateOfServices.setRatingOfServices(rateOfServices);
        cmdBack = new Command("Back", Command.BACK, 0);
        addCommand(cmdBack);
        setCommandListener(this);
    }

    public void setDataFrom(Reviews r) {
        this.obReviews = r;
        for (int i = 0; i < typeOfMeal.length; i++) {
            if (typeOfMeal[i].equals(r.getTypeOfMeal())) {
                cbbTypeOfMeal.setSelectedIndex(i, true);
                break;
            }
        }
        dateOfReview.setDate(r.getDate());
        txtCostOfMeal.setString(r.getCost() + "");
        overallRate.setRatePoint(r.getOverallRating());
        rateOfAtmosphere.setRatePoint(r.getRateOfAtmosphere());
        rateOfFood.setRatePoint(r.getRateOfFood());
        rateOfServices.setRatePoint(r.getRateOfServices());
        txtComment.setString(r.getComment());

    }
    private FromViewEstablistment frmViewEst;

    public void commandAction(Command c, Displayable d) {
        if (c == cmdBack) {
            if (STAGE_FORM == ADD) {
                frmListEst = new FromListEstablishments(curDisplay);
                Display.getDisplay(curDisplay).setCurrent(frmListEst);
            } else if (STAGE_FORM == EDIT) {
                frmViewEst = new FromViewEstablistment(curDisplay);
                frmViewEst.setEstablishment(est);
                Display.getDisplay(curDisplay).setCurrent(frmViewEst);
            }
        } else if (c == cmdAdd) {
            boolean check = checkValid();

            if (check) {
                Reviews re = new Reviews();
                re.setEstId(est.getId());
                re.setDate(dateOfReview.getDate());
                re.setTypeOfMeal(cbbTypeOfMeal.getString(cbbTypeOfMeal.getSelectedIndex()));
                re.setOverallRating(overallRate.getRatePoint());
                re.setCost(Integer.parseInt(txtCostOfMeal.getString()));
                re.setRateOfAtmosphere(rateOfAtmosphere.getRatePoint());
                re.setRateOfServices(rateOfServices.getRatePoint());
                re.setRateOfFood(rateOfFood.getRatePoint());
                re.setComment(txtComment.getString());
                boolean isValid = reviewBO.add(re);
                if (isValid) {
                    estBO.addElementList(re);
                    msg = new Alert("Message", "Add new a Review successful", null, AlertType.ALARM);
                    cmdDone = new Command("Done", Command.OK, 1);
                    msg.setTimeout(2000);
                    msg.setCommandListener(this);
                    Display.getDisplay(curDisplay).setCurrent(msg, this);
                    Thread t = new Thread(this);
                    flag = false;
                    t.start();
                } else {
                    msg = new Alert("Error!", "Add new a Review Error, Please try again!", null, AlertType.ERROR);
                    Display.getDisplay(curDisplay).setCurrent(msg, this);
                }
            }
        } else if (c == cmdEdit) {
            msg = new Alert("Notify!", "Do you want edit?", null, AlertType.CONFIRMATION);
            msg.setTimeout(Alert.FOREVER);
            cmdOk = new Command("OK", Command.OK, 1);
            cmdCancel = new Command("Cancel", Command.CANCEL, 0);
            msg.addCommand(cmdOk);
            msg.addCommand(cmdCancel);
            msg.setCommandListener(this);
            Display.getDisplay(curDisplay).setCurrent(msg, this);
        } else if (c == cmdOk) {
            editReview();
        } else if (c == cmdDone) {
            flag = true;
            backReview(est);
        }
    }

    private boolean checkValid() {
        String cost = txtCostOfMeal.getString();
        if (cost.length() <= 0) {
            msg = new Alert("Error!", "Cost of food is not empty", null, AlertType.ERROR);
            Display.getDisplay(curDisplay).setCurrent(msg, this);
            return false;
        }
        return true;
    }

    private void editReview() {
        boolean check = checkValid();
        if (check) {
            Reviews re = new Reviews();
            re.setEstId(est.getId());
            re.setDate(dateOfReview.getDate());
            re.setTypeOfMeal(cbbTypeOfMeal.getString(cbbTypeOfMeal.getSelectedIndex()));
            re.setOverallRating(overallRate.getRatePoint());
            re.setCost(Integer.parseInt(txtCostOfMeal.getString()));
            re.setRateOfAtmosphere(rateOfAtmosphere.getRatePoint());
            re.setRateOfServices(rateOfServices.getRatePoint());
            re.setRateOfFood(rateOfFood.getRatePoint());
            re.setComment(txtComment.getString());
            boolean isValid = reviewBO.edit(obReviews, re);
            if (isValid) {
                //estBO.addElementList(re);
                editReviewInEstablishment(re);
                msg = new Alert("Message!", "Edit a Review successful", null, AlertType.ALARM);

                msg.setTimeout(2000);
                Display.getDisplay(curDisplay).setCurrent(msg, this);
                Thread t = new Thread(this);
                flag = false;
                t.start();
            } else {
                msg = new Alert("Error!", "Edit a Review Error, Please try again!", null, AlertType.ERROR);
                Display.getDisplay(curDisplay).setCurrent(msg, this);
            }
        }
    }

    public void editReviewInEstablishment(Reviews re) {
        Vector v = est.getListReview();
        for (int i = 0; i < est.getListReview().size(); i++) {
            Reviews rObj = (Reviews) est.getListReview().elementAt(i);
            if (obReviews.toString().equals(rObj.toString())) {
                est.getListReview().setElementAt(re, i);
                break;
            }
        }
        estBO.EditReviewInEstablishment(est);
    }

    private void backReview(Establishment est) {
        viewEst = new FromViewEstablistment(curDisplay);
        viewEst.setEstablishment(est);
        Display.getDisplay(curDisplay).setCurrent(viewEst);
    }
    private boolean flag = false;

    public void run() {
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
            }
            if (!flag) {
                flag = true;
                backReview(est);
            } else {
                break;
            }
        }
    }
}
